package com.gqz.springbootdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gqz.springbootdemo.mapper.StudentMapper;
import com.gqz.springbootdemo.pojo.Student;
import com.gqz.springbootdemo.service.CourseService;
import com.gqz.springbootdemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gqz20
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private CourseService courseService;

    @Override
    public List<Student> findList(Long id) {
        List<Student> students = getBaseMapper().findList(id);
        return students;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStudent(Student student) {
        boolean save = save(student);
        if (!save) {
            throw new RuntimeException("add student error");
        }
        student.getCourses().forEach(course -> {
            getBaseMapper().updateAssociation(student.getId(), course.getId());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudent(Student student) {
        boolean b = updateById(student);
        if (!b) {
            throw new RuntimeException("update student error");
        }
        getBaseMapper().deleteAssociation(student.getId());
        student.getCourses().forEach(course -> {
            getBaseMapper().updateAssociation(student.getId(), course.getId());
        });
    }
}




